<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TODO List</title>
    <style>
        .con {
            width: 400px;
            margin: 0 auto;
        }
    </style>
</head>

<body>
    <div class="con">
        <h1>TODO LIST</h1>
        <div>
            <input type="text" id="datainput" />
            <button id="btn">add</button>
        </div>
        <table id="tb">
            <tr>
                <th>data</th>
                <th>manager</th>
            </tr>
        </table>
    </div>
</body>
<script>
    let btn = document.getElementById("btn");
    // 前端数据合法性校验
    btn.onclick = function () {
        let val = document.getElementById("datainput").value;
        let addData = { msg: val }
        fetch("http://192.168.174.166:8080/api/adddata", {
            method: "POST",
            body: JSON.stringify(addData)
        }).then(res => res.json())
            .then(res => {
                console.log(res)
            })
    }

    window.onload = function () {
        fetch("http://192.168.174.166:8080/api/list").then(res => res.json())
            .then(res => {
                let tb = document.getElementById("tb")
                tb.innerHTML = "";
                for (let i = 0; i < res.length; i++) {
                    let trObj = document.createElement("tr");
                    trObj.innerHTML = "<td>" +
                        res[i].msg + "</td>" +
                        "<td><button id='" + res[i].id + "'>删除</button></td>";

                    tb.appendChild(trObj);
                }
            })
    }
    tb.onclick = function (e) {
        let btn = e.target;
        let id = btn.getAttribute("id");
        delData(btn, id);
    }
    function delData(btn, id) {
        //将id传至服务端 发起请求删除数据
        fetch("http://192.168.174.166:8080/api/del", {
            method: "DELETE",
            body: JSON.stringify({ id: id })
        }).then(res => res.json())
            .then(res => {
                if (res.status == "ok") {
                    btn.parentNode.parentNode.parentNode.removeChild(btn.parentNode.parentNode);
                }
            })
    }
</script>

</html>